<?php

namespace App\Http\Controllers;

use App\Models\Attachment;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class AttachmentController extends Controller
{
    /**
     *  附件资源详情
     */
    public function show(Attachment $attachment, Request $request)
    {
        // 获取对应的 pdf 文件
        $file = file_get_contents(storage_path('app/public/') . $attachment->url);
        $fileMime = $this->getMime($attachment->ext);
        $typeArr = ['Content-Type' => $fileMime];
        return new Response($file, 200, $typeArr);
    }

    /**
     *  根据文件类型获取 fileMine
     * @param $ext
     * @return string
     */
    public function getMime($ext)
    {
        if ($ext == 'png') {
            $fileMime = 'image/png';
        } elseif ($ext == 'jpeg') {
            $fileMime = 'image/jpeg';
        } elseif ($ext == 'jpg') {
            $fileMime = 'image/jpeg';
        } elseif ($ext == 'wav') {
            $fileMime = 'audio/x-wav';
        } elseif ($ext == 'svg') {
            $fileMime = 'image/svg+xml';
        } elseif ($ext == 'pdf') {
            $fileMime = 'application/pdf';
        } else {
            $fileMime = 'image/jpeg';
        }
        return $fileMime;
    }
}
